import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { timer } from 'rxjs';

import { RouterStateService, LockScreenService, LockScreenState } from '@core/base';
import { fnIsFormInvalid } from '@util/form';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { CountdownEvent } from 'ngx-countdown';

import { PasswordFormComponent } from './password-form.component';

@Component({
  selector: 'app-unlock',
  templateUrl: './unlock.component.html'
})
export class UnlockComponent implements OnInit {
  @ViewChild('pwdForm')
  pwdForm!: PasswordFormComponent;
  timeout = 15; // 秒
  lockScreenState!: LockScreenState;

  constructor(
    private messageSrc: NzMessageService,
    private router: Router,
    private modal: NzModalRef,
    private routerStateSrc: RouterStateService,
    private lockScreenSrc: LockScreenService
  ) {}

  ngOnInit(): void {
    this.lockScreenSrc.lockScreenStateChanged$.subscribe(data => {
      this.lockScreenState = data;
    });
  }

  onUnlock(): void {
    if (fnIsFormInvalid(this.pwdForm.form)) {
      return;
    }

    if (this.lockScreenState.locked) {
      const password = this.pwdForm.password?.value;
      // 密码正确则解锁
      if (this.lockScreenState.password !== password) {
        this.messageSrc.error('密码校验失败，请重新输入');
        return;
      }

      timer(100).subscribe(() => {
        this.closeForm();
        this.router.navigateByUrl(this.routerStateSrc.previouRouter);
      });

      // 释放锁屏
      this.lockScreenSrc.publish({ locked: false });
    }
  }

  onCancel(): void {
    this.closeForm();
  }

  closeForm(): void {
    this.modal.destroy();
  }

  handleCountDown(event: CountdownEvent): void {
    if (event.action === 'done') {
      this.closeForm();
    }
  }
}
